package com.dzl.timer;

import com.alibaba.fastjson.JSONObject;
import com.dzl.constant.ApiFuLuConstant;
import com.dzl.fulu.sup.open.api.core.utils.JSONUtil;
import com.dzl.fulu.sup.open.api.model.InputOrderGetDto;
import com.dzl.fulu.sup.open.api.model.response.DefaultClientResponse;
import com.dzl.fulu.sup.open.api.sdk.DefaultOpenApiClient;
import com.dzl.integral.service.WelfareIntegralRecordService;
import com.dzl.order.pojo.WelfareOrder;
import com.dzl.order.service.WelfareOrderExpService;
import com.dzl.order.service.WelfareOrderService;
import com.dzl.util.EmptyUtils;
import com.dzl.voucherSecret.service.WelfareVoucherSecretService;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 定时任务类
 * @author caobucao
 * @date 2021/5/26 15:32
 */
@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Service
public class TimerTask {

    @Autowired
    private WelfareVoucherSecretService welfareVoucherSecretService;
    @Autowired
    private WelfareOrderService welfareOrderService;
    @Autowired
    private WelfareOrderExpService welfareOrderExpService;
    @Autowired
    private WelfareIntegralRecordService welfareIntegralRecordService;

    /**
     * 券密过期定时任务
     * @date 2021/5/28 9:20
     * @author caobucao
     */
    @Async
    @Scheduled(cron = "0 1 0 * * ?") //0 1 0 * * ?
    @Transactional(rollbackFor = Exception.class)
    public void voucherSecretTimer() {
        log.info("-----------------------每天凌晨0点0分执行券密过期任务，任务开始-----------------------");
        int count = welfareVoucherSecretService.updateIsExpiredByExpiredTime();
        log.info("-----------------------每天凌晨0点0分执行券密过期任务，共过期 " + count + " 条券密，任务结束-----------------------");
    }

    /**
     * 卡密过期定时任务
     * @date 2021/5/28 9:20
     * @author caobucao
     */
    /*@Async
    @Scheduled(cron = "0 1 0 * * ?") //
    @Transactional(rollbackFor = Exception.class)
    public void cardSecretTimer() {
        log.info("-----------------------每天凌晨0点0分执行卡密过期任务，任务开始-----------------------");
        int count = welfareCardSecretService.updateIsExpiredByExpiredTime();
        log.info("-----------------------每天凌晨0点0分执行卡密过期任务，共过期 " + count + " 条卡密，任务结束-----------------------");
    }*/

    /**
     * 兑换券定时过期任务
     * @date 2021/7/23 11:58
     * @author caobucao
     */
   /* @Async
    @Scheduled(cron = "0 1 0 * * ?") //
    @Transactional(rollbackFor = Exception.class)
    public void exchangeSecretTimer() {
        log.info("-----------------------每天凌晨0点0分执行兑换券过期任务，任务开始-----------------------");
        int count = welfareExchangeSecretService.updateIsExpiredByExpiredTime();
        log.info("-----------------------每天凌晨0点0分执行兑换券过期任务，共过期 " + count + " 条兑换券，任务结束-----------------------");
    }
*/

    /**
     * 订单超时取消任务
     * @author ChenLong
     * @date 2021-06-09 14:39:39
     **/
    @Async
    @Scheduled(cron = "0 */5 * * * ?") //五分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void orderCancelTimer() {
        log.info("-----------------------订单超时取消任务开始-----------------------");
        int count = welfareOrderService.updateOrderCancelExpiredTime();
        log.info("-----------------------订单超时取消任务，共取消 " + count + " 条订单，任务结束-----------------------");
    }

    /**
     * 订单T+7自动发货定时任务
     * @date 2021/7/5 9:30
     * @author caobucao
     */
    @Async
    @Scheduled(cron = "0 */5 * * * ?") //五分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void orderDeliveryTimer() {
        log.info("-----------------------订单超时收货任务开始-----------------------");
        int count = welfareOrderService.updateOrderDelivery();
        log.info("-----------------------订单超时收货任务，共收货 " + count + " 条订单，任务结束-----------------------");
    }

    /**
     * 福禄订单刷新充值状态
     * @date 2021/8/20 0020 9:56
     * @author wangjian
     */
    @Async
    @Scheduled(cron = "0 */1 * * * ?") //1分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void waitFor() {
        log.info("-----------------------刷新福禄订单充值状态开始-----------------------");
        //查询所有在充值中的福禄订单
        List<String> list = welfareOrderExpService.selectFuluOrderState();
        if (EmptyUtils.isNotEmpty(list)) {
            for (String orderNo : list) {
                try {
                    //调用订单查询接口
                    DefaultOpenApiClient client =
                            new DefaultOpenApiClient(ApiFuLuConstant.URL, ApiFuLuConstant.APP_KEY, ApiFuLuConstant.SYS_SECRET, ApiFuLuConstant.OPEN_API_ORDER_GET);
                    InputOrderGetDto dto = new InputOrderGetDto();
                    dto.setCustomerOrderNo(orderNo);
                    client.setBizObject(dto);
                    log.info("queryOrder map: " + dto);
                    DefaultClientResponse response = JSONUtil.fromJSON(client.excuteAsync().get(), new TypeToken<DefaultClientResponse>() {
                    });
                    if (JSONObject.parseObject(client.excuteAsync().get()).getString("code").equals("0")) {
                        String result = response.getResult();
                        String orderState = JSONObject.parseObject(result).getString("order_state");
                        WelfareOrder welfareOrder = new WelfareOrder();
                        welfareOrder.setOrderNo(orderNo);
                        List<WelfareOrder> select = welfareOrderService.select(welfareOrder);
                        if (EmptyUtils.isNotEmpty(select)) {
                            Integer id = select.get(0).getId();
                            Integer status = 2;
                            if (orderState.equals("success")) {
                                status = 3;
                            } else if (orderState.equals("processing")) {
                                status = 2;
                            } else if (orderState.equals("failed")) {
                                status = 4;
                            } else if (orderState.equals("untreated")) {
                                status = 2;
                            }
                            welfareOrderExpService.updateStatus(id, status);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("-----------------------共刷新 " + list.size() + " 条订单，任务结束-----------------------");
    }

    /**
     * 充值积分两小时后积分自动到账
     * @date 2021/9/7 0007 16:13
     * @author wangjian
     */
    @Async
    @Scheduled(cron = "0 */5 * * * ?") //五分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void integralRechargeTimer(){
        log.info("-----------------------充值积分自动到账任务开始-----------------------");
        Integer count = welfareIntegralRecordService.integralRechargeSuccess();
        log.info("-----------------------充值积分自动到账任务，共充值到账 " + count + " 条积分，任务结束-----------------------");
    }

}
